import gql from 'graphql-tag'

function validator(model) {
  const {
    table,
    columns = []
  } = model || {}

  if (typeof table !== 'string') {
    throw new Error('Field [model.table] must be string.')
  }

  if (!Array.isArray(columns)) {
    throw new Error('Field [model.columns] must be array.')
  }

  return { table, columns }
}

function parse(key) {
  const steps = key.replace(/\.+/g, '.').split('.')
  let s = steps.pop()

  while (steps.length) {
    s = `${steps.pop()} {\n${s}\n}\n`
  }

  return s
}

export function createPkQuery(model, idKey = 'id', idType) {
  const { table, formInputs = {} } = model || {}
  const keys = []

  for (let key in formInputs) {
    const input = formInputs[key] || {}

    if (!key || input['type'] === 'password') {
      continue
    }
    if (Array.isArray(input['_keys'])) {
      keys.push(`${key} ${input['_sortby'] ? '(order_by: {' + input['_sortby'] + '})' : '' } {
        ${input['_keys'].join('\n')}
      }`)
    } else {
      keys.push(key)
    }
  }

  return gql`
    query ($${idKey}: ${idType || (idKey === 'id' ? 'Int' : 'uuid')}!) {
      ${table} (where: { ${idKey}: { _eq: $${idKey}} }) {
        ${keys.join('\n')}
      }
    }
  `
}

export function createPageQuery(model) {
  const { table, columns } = validator(model)
  const keys = []

  for (let i = 0; i < columns.length; i += 1) {
    if (columns[i].key) {
      keys.push(
        parse(columns[i].key)
      )
    }
  }

  return gql`
    query ($limit: Int!, $offset: Int!, $where: ${table}_bool_exp, $orderBy: [${table}_order_by!] = { create_at: desc }) {
      ${table} (limit: $limit, offset: $offset, where: $where, order_by: $orderBy) {
        ${keys.join('\n')}
      }
      ${table}_aggregate (where: $where) {
        aggregate {
          count
        }
      }
    }
  `
}
